package com.shareit.ocr.service;

import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shareit.ocr.domain.SimulatorRequestInfo;
import com.shareit.ocr.domain.simulator.BaseSimulator;
import com.shareit.ocr.domain.simulator.SimulatorFactory;
import com.shareit.ocr.domain.template.InvoiceDataTemplate;
import com.shareit.ocr.domain.template.InvoiceDataTemplateFactory;
import com.shareit.ocr.enums.ResultEnum;
import com.shareit.ocr.exception.SimulatorException;
import com.shareit.ocr.properties.SimulatorProperties;
import com.shareit.ocr.util.InvoiceQueryUtil;

@Service
public class SimulatorService {
	
	private final static Logger logger = LoggerFactory.getLogger(SimulatorService.class);
	@Autowired
	private SimulatorProperties simulatorProperties;
	
	public InvoiceDataTemplate simulate(SimulatorRequestInfo sri) throws Exception {
		checkRequestValid(sri);
		InvoiceDataTemplate dataTemplate = InvoiceDataTemplateFactory.createInstance(sri);
		List<BaseSimulator> simulators = SimulatorFactory.createInstances(simulatorProperties.getSimulatorType());
		for(BaseSimulator simulator : simulators) {
			try {
				logger.info("启动Simulator：" + simulator.getId());
				simulator.setSimulatorProperties(simulatorProperties);
				simulator.start(dataTemplate);
				if(simulator.getStatus()) {
					logger.info("Simulator执行成功:" + simulator.getId());
					break;
				}
			}finally {
				logger.info("关闭Simulator：" + simulator.getId());
				simulator.close();
			}
		}
		
		return  dataTemplate;
	}
	
	
	public void checkRequestValid(SimulatorRequestInfo sri) throws Exception {
		
		String fplx = InvoiceQueryUtil.getInvoiceType(sri.getFpdm());
		if (!Arrays.asList(simulatorProperties.getAcceptInvoiceType().split(",")).contains(fplx)) {
			throw new SimulatorException(ResultEnum.VALID_FPTYPE_ERROR);
		}
		
	}
	

}
